package base.http.utils;

import android.app.Activity;
import android.content.Context;
import android.os.Build;


import com.tange.ai.iot.client.gnssa.R;

import org.reactivestreams.Subscription;

import io.reactivex.functions.Consumer;

/**
 * Created by LZH On 2019/3/19
 */
public class ConsumerDialog implements Consumer<Subscription> {

    private BaseDialog dialog;
    private Context mContext;

    public ConsumerDialog(Context mContext) {
        this.mContext=mContext;
        dialog = new BaseDialog(mContext, R.layout.layout_loading);
    }

    public void setCancelDialog(boolean isCancel){
        dialog.setCancelable(isCancel);
    }

   @Override
    public void accept(Subscription subscription) throws Exception {
        showDialog();
    }

    public void setCancelable(boolean cancelable){
        if(dialog!=null){
            dialog.setCancelable(cancelable);
            dialog.setCanceledOnTouchOutside(false);
        }
    }

    public boolean isShowing() {
        if (dialog != null) {
            return dialog.isShowing();
        } else {
            return false;
        }
    }

    public void dismiss() {
        if (dialog != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                if(mContext!=null && ((Activity)mContext).isDestroyed()){
                    return;
                }
            }
            dialog.dismiss();
        }
    }

    public void showDialog() {
        if (dialog != null) {
            if(!((Activity)dialog.mContext).isFinishing()) {
                dialog.show();
                dialog.setCancelable(true);
            }
        }
    }
}
